package org.jground.rx.ui.zk;

import java.util.EventObject;

import org.jground.rx.IRXObject;
import org.jground.rx.RXLangStrings;
import org.jground.rx.RXObjectService;
import org.jground.rx.ui.pref.PrefEventListener;
import org.jground.zk.util.ZKUtils;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Menu;
import org.zkoss.zul.Menuitem;
import org.zkoss.zul.Menupopup;

public class UIRecent implements PrefEventListener, EventListener {

    private static RXLangStrings recentStr = new RXLangStrings("Recent...", "en", "Recent...", "de", "Letzte...");
    private static String OID = "OID";

    private UIFrame uiFrame;
    //
    private Menu recentMenu;
    private Menupopup recentMenupopup;

    public UIRecent(UIFrame uiFrame) {
        this.uiFrame = uiFrame;
        recentMenu = new Menu(recentStr.toString());
        recentMenu.setImageContent(UIStyles.getInstance().getAImage(UIStyles.ImageKey.recent16));
        recentMenupopup = new Menupopup();
        recentMenupopup.setParent(recentMenu);
        uiFrame.getPrefService().addListener(this);
       
    }

    public void setParent(Component parent) {
        recentMenu.setParent(parent);
    }

    public void newPrefArrived(EventObject event) {
        ZKUtils.removeAllChildren(recentMenupopup);
        for (Long oid : uiFrame.getPrefService().getRecentViewed()) {
            IRXObject rxd = RXObjectService.getInstance().getById(oid);         
            Menuitem mi = new Menuitem(uiFrame.getUISynopsisRendererFactory().toString(rxd));
            mi.addEventListener(Events.ON_CLICK, this);
            mi.setParent(recentMenupopup);
            mi.setAttribute(OID, oid);
        }
    }

    public void onEvent(Event event) throws Exception {
        Long oid = (Long) event.getTarget().getAttribute(OID);
        uiFrame.openView(oid, true);
    }

}
